<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vue入门指南——组件基础之定义与使用</title>
    <link rel="stylesheet" href="common.css" />
    <script type="importmap">
      {
        "imports": {
          "vue": "https://lib.baomitu.com/vue/latest/vue.esm-browser.js"
        }
      }
    </script>
  </head>
  <body>
    <div id="app">
      <p>{{ message }}</p>
      <p>
        <my-counter></my-counter>
        <my-counter></my-counter>
      </p>
      <p>
        <my-post title="标题1"></my-post>
        <my-post title="标题2"></my-post>
      </p>
      <p>
        <my-post
          v-for="post in posts"
          :key="post.id"
          :title="post.title"
        ></my-post>
      </p>
      <p>
        <my-emit @foo-emit="foobar"></my-emit>
      </p>
      <p>
        <my-slot>显示在插槽中的数据</my-slot>
      </p>
    </div>
    <script type="module">
      import { createApp } from "vue";

      let app = createApp({
        data() {
          return {
            message: "组件基础示例",
            posts: [
              { id: 1, title: "标题111" },
              { id: 2, title: "标题222" },
              { id: 3, title: "标题333" },
            ],
          };
        },
        methods: {
          foobar(data) {
            console.log(
              `在父组件中监听子组件提供的事件，同时还是可以从子组件向父组件传递数据:${data}`
            );
          },
        },
      });

      app.component("MyCounter", {
        template: `
            <button @click ="add">已点击{{counter}} 次 </button>
        `,
        data() {
          return {
            counter: 0,
          };
        },
        methods: {
          add() {
            this.counter++;
          },
        },
        mounted() {
          console.log("组件MyCounter挂载");
        },
      });
      app.component("MyPost", {
        template: `<h3>{{title}}</h3> `,
        props: ["title"],
        mounted() {
          console.log(this.title);
        },
      });

      app.component("MyEmit", {
        template: `<button @click="foo">子组件监听事件</button>`,
        emits: ["foo-emit"],
        methods: {
          foo() {
            this.$emit("foo-emit", "来自MyEmit组件数据");
          },
        },
      });

      app.component("MySlot", {
        template: `
          <div>
            <h3>插槽Slot</h3>
            <slot/>  
            <br>
            <slot/>
          </div>
        `,
      });

      app.mount("#app");
    </script>
  </body>
</html>
